package ants_service

import (
	"gitee.com/lianyi_work/service"
	"github.com/samber/lo"
	"log"
	"os"
)

var runFunc func()

type program struct{}

func (p *program) Start(s service.Service) error {
	go p.run()
	return nil
}
func (p *program) run() {
	run()
}

func run() {
	if runFunc != nil {
		runFunc()
	}
}

func (p *program) Stop(s service.Service) error {
	return nil
}

func RunService(name, display_name string, f func()) {
	runFunc = f

	args_len := len(os.Args)
	args_lists := make([]string, 0)
	if args_len == 1 {
		run()
	}

	var s service.Service
	var err error

	dir, _ := os.Getwd()
	svcConfig := &service.Config{
		Name:             name,
		DisplayName:      "",
		Description:      display_name,
		WorkingDirectory: dir,
	}
	prg := &program{}

	if lo.Contains(service.ControlAction[:], os.Args[1]) {
		if os.Args[1] == "install" {
			args_lists = append(args_lists, os.Args[2:]...)
		}
		svcConfig.Arguments = args_lists

		s, err = service.New(prg, svcConfig)
		if err != nil {
			log.Fatal(err)
		}
		if len(os.Args) > 1 {
			err = service.Control(s, os.Args[1])
			if err != nil {
				log.Fatal(err)
			}
			return
		}
	} else {
		s, err = service.New(prg, svcConfig)
	}

	s.Run()
}
